import { resolve } from 'path'
import { config } from 'dotenv'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import graphql from '@rollup/plugin-graphql'
import viteCompression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'

import Components from 'unplugin-vue-components/vite'
import {
  NaiveUiResolver,
  ArcoResolver
} from 'unplugin-vue-components/resolvers'

const envConfig = config({
  path: resolve(__dirname, '../.env')
})?.parsed

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  const config = {
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: resolve(__dirname, './src') + '/'
        }
      ]
    },
    server: {
      port: 3088,
      proxy: {
        '^/api|^/unsafe|^/v1/graphql|^/gf': {
          target: 'http://127.0.0.1:7001',
          xfwd: true
        },
        // office
        '^/web-apps|^/6.3.2-2|^/cache|^/sdkjs|^/doc': {
          target: 'http://127.0.0.1:7001',
          xfwd: true
        },
        ['^/' + envConfig.MINIO_BUCKET]: {
          target: 'http://127.0.0.1:7001',
          xfwd: true
        }
      }
    },
    build: {
      assetsDir: 'static',
      cssCodeSplit: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'static/js/[hash].js',
          entryFileNames: 'static/js/[hash].js',
          assetFileNames: 'static/[hash].[ext]',
          manualChunks(id) {
            // if (
            //   id.includes('graphql') ||
            //   id.includes('node_modules/ky')
            // ) {
            //   return 'request'
            // }
            if (
              id.includes('@arco-design') ||
              id.includes('naive-ui')
            ) {
              return 'components'
            }
            if (id.includes('node_modules')) {
              return 'vendor'
            }
          }
        }
      }
    },
    define: {
      'process.TOKEN_KEY': JSON.stringify(envConfig.ADMIN_TOKEN_KEY),
      'process.REFRESH_TOKEN_KEY': JSON.stringify(envConfig.ADMIN_REFRESH_TOKEN_KEY)
    }
  }

  const plugins = [
    vue(),
    graphql(),
    Components({
      resolvers: [
        NaiveUiResolver(),
        ArcoResolver()
      ]
    }),
    legacy({
      polyfills: ['es.promise', 'es.promise.finally', 'es.object.assign', 'es/map', 'es/set'],
      // modernPolyfills: ['es.promise.finally'],
      additionalLegacyPolyfills: ['unfetch/polyfill/polyfill.mjs']
    })
  ]

  if (command === 'build') {
    plugins.push(viteCompression({
      algorithm: 'brotliCompress'
    }))
  }

  return {
    ...config,
    plugins
  }
})
